// 核心配置参数
const selectors = [
  { selector: "#btn1", message: "点此【新增】数据！" },
  { selector: "#btn2", message: "小心【删除】数据！" },
  { selector: "#btn3", message: "可通过此按钮【修改】数据！" },
  { selector: "#btn4", message: "一键【完成】所有操作！" },
];

const guideModal = document.getElementById("guideModal");
const guideBox = document.getElementById("guideBox");
const guideMessage = document.getElementById("guideMessage");
const guidePrevBtn = document.getElementById("guidePrevBtn");
const guideNextBtn = document.getElementById("guideNextBtn");

let preNode = null;
let index = 0;
let show = true;

document.addEventListener("DOMContentLoaded", () => {
  genGuide();
});

// 页面内容发生变化时，重新计算位置
window.addEventListener("resize", () => genGuide());
window.addEventListener("scroll", () => genGuide());

guidePrevBtn.addEventListener("click", () => {
  changeStep(true);
});
guideNextBtn.addEventListener("click", () => {
  changeStep(false);
});

function changeStep(isPre) {
  isPre ? index-- : index++;
  currNode = null;
  genGuide();
}

function genGuide() {
  // 所有指引完毕
  if (index > selectors.length - 1) {
    show = false;
    return;
  }

  // 修改上一个节点的 z-index
  if (preNode) {
    preNode.style = `z-index: 0;`;
  }

  // 获取目标节点信息
  const target = (preNode = document.querySelector(selectors[index].selector));
  target.style = ` position: relative; z-index: 1000;`;
  const { x, y, width, height } = target.getBoundingClientRect();

  // 指引相关
  if (guideBox) {
    const halfClientHeight = guideBox.clientHeight / 2;
    guideMessage.innerText = selectors[index].message;
    guideBox.style = ` left:${x + width + 10}px; top:${
      y <= halfClientHeight ? y : y - halfClientHeight + height / 2
    }px; `;
  }
}
